<template>
    <FormData ref="formDataRef" :formData="formData" :rules="rules" :title="popupTitle" @submit="handleSubmit"
        @close="handleClose">

        <el-form-item label="菜单属性" prop="type">
            <el-radio-group v-model="formData.type">
                <el-radio :value="MenuType.CATALOG">目录</el-radio>
                <el-radio :value="MenuType.MENU">菜单</el-radio>
                <el-radio :value="MenuType.BUTTON">按钮</el-radio>
            </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.type !== MenuType.BUTTON" label="图标" prop="fromData.icon">
            <IconPicker v-model="formData.icon" />
        </el-form-item>

        <el-form-item label="权限名称" prop="name">
            <Input v-model="formData.name" placeholder="请输入权限名称" />
        </el-form-item>

        <el-form-item v-if="formData.type !== MenuType.BUTTON" label="父级权限" prop="parent_id">
            <el-tree-select 
                v-model="formData.parent_id" 
                :data="parentList" 
                :props="{label: 'name', value: 'id'}" 
                :render-after-expand="false"
                :default-expand-all="true"
                @change="handleParentChange"
            />
        </el-form-item>

        <el-form-item v-if="formData.type !== MenuType.CATALOG && formData.type !== MenuType.BUTTON" label="组件地址"
            prop="component">
            <el-select clearable filterable v-model="formData.component" placeholder="请选择组件地址">
                <el-option v-for="(value, key) in modules" :key="key" :label="key" :value="key" />
            </el-select>
        </el-form-item>

        <el-form-item label="路由地址" prop="path" v-if="formData.type !== MenuType.BUTTON">
            <Input v-model="formData.path" placeholder="请输入路由地址" />
        </el-form-item>

    </FormData>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { MenuType } from '@/utils/enums/appEnums'
import Input from '@/components/formData/components/input.vue'
import { savePermission, updatePermission } from '@/api/system/rbac/permission'
import type { FormInstance } from 'element-plus'
import FormData from '@/components/formData/index.vue'
import { filteredModules } from '@/utils/router'
import { getPermissionList } from '@/api/system/rbac/permission'
import axios from 'axios'

const props = defineProps({
    lists: {
        type: Array,
        default: () => []
    }
})

// 递归过滤按钮类型
const filterButtons = (items: any[]): any[] => {
    return items.map(item => {
        // 如果是按钮类型，返回 null
        if (item.type === MenuType.BUTTON) {
            return null
        }
        // 创建新的对象，避免修改原始数据
        const newItem = { ...item }
        // 如果有子菜单，递归处理
        if (newItem.children && newItem.children.length) {
            newItem.children = filterButtons(newItem.children).filter(Boolean)
        }
        return newItem
    }).filter(Boolean) // 过滤掉 null 值
}

// 父级列表
const parentList = ref<any[]>([])

// 更新父级列表
const updateParentList = () => {
    const filteredList = filterButtons(props.lists)
    parentList.value = [
        { id: 0, name: '顶级菜单', type: 1, parent_id: 0, path: '', component: '', icon: '', sort: 0, status: 1, is_show: 1, is_cache: 1, permission: '', button_ids: [] },
        ...filteredList
    ]
}

const modules = computed(() => {
    const rawModules = filteredModules()
    // 将对象转换为数组进行排序
    const sortedEntries = Object.entries(rawModules).sort(([keyA], [keyB]) => {
        return keyA.length - keyB.length
    })
    // 转回对象
    return Object.fromEntries(sortedEntries)
})

interface FormDataInstance {
    formRef: FormInstance
    open: () => void
    close: () => void
}

const formDataRef = ref<FormDataInstance>()
const emits = defineEmits(['success', 'close'])

// 表单模式：add-新增，edit-编辑
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value === 'add' ? '新增权限' : '编辑权限'
})

interface PermissionItem {
    id: number
    name: string
    type: number
    parent_id: number
    path: string
    component: string
    icon: string
    sort: number
    status: number
    is_show: number
    is_cache: number
    permission: string
    button_ids: number[]
    children?: PermissionItem[]
}

interface FormData {
    id: number
    name: string
    type: number
    parent_id: number
    path: string
    component: string
    icon: string
    sort: number
    status: number
    is_show: number
    is_cache: number
    permission: string
    button_ids: number[]
    children?: PermissionItem[]
}

const formData = ref<FormData>({
    id: 0,
    name: '',
    type: 1,
    parent_id: 0,
    path: '',
    component: '',
    icon: '',
    sort: 0,
    status: 1,
    is_show: 1,
    is_cache: 1,
    permission: '',
    button_ids: []
})

// 表单验证规则
const rules = {
    name: [
        { required: true, message: '请输入权限名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    path: [
        { required: true, message: '请输入路由路径', trigger: 'blur' }
    ],
    component: [
        { required: true, message: '请输入组件路径', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请选择权限类型', trigger: 'change' }
    ],
    icon: [
        { required: true, message: '请选择图标', trigger: 'change' }
    ],
    sort: [
        { required: true, message: '请输入排序', trigger: 'blur' },
        { type: 'number', message: '排序必须为数字', trigger: 'blur' }
    ]
}

// 打开弹窗
const open = (type: string = 'add') => {
    mode.value = type
    formDataRef.value?.formRef?.resetFields()
    // 在打开弹窗前更新父级列表
    updateParentList()
    formDataRef.value?.open()
}

// 设置表单数据
const setFormData = (data: Partial<FormData>) => {
    formData.value = {
        ...formData.value,
        ...data,
        parent_id: data.parent_id || 0
    }
}

// 提交表单
const handleSubmit = async (loading: { value: boolean }) => {
    try {
        loading.value = true
        const res = mode.value === 'add' ? await savePermission(formData) : await updatePermission(formData)
        ElMessage.success('保存成功')
        emits('success')
        formDataRef.value?.close()
    } catch (error) {
        console.error('保存失败:', error)
    } finally {
        loading.value = false
    }
}

// 关闭弹窗
const handleClose = () => {
    emits('close')
}

// 暴露方法给父组件
defineExpose({
    open,
    setFormData
})

// 处理父级选择
const handleParentChange = (value: number) => {
    // 如果选择了顶级菜单，清空父级ID
    if (value === 0) {
        formData.value.parent_id = 0
    }
}

// 监听 lists 变化
watch(() => props.lists, () => {
    updateParentList()
}, { deep: true })

// 移除 onMounted 中的初始化
onMounted(() => {
    // 初始化父级列表
    updateParentList()
})

// 监听父级ID变化
watch(() => formData.value.parent_id, (newVal) => {
    // 如果选择了顶级菜单，清空父级ID
    if (newVal === 0) {
        formData.value.parent_id = 0
    }
})
</script>
